import { View, Image, Canvas, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { Component } from 'react';

import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import { IPLAND_OSS_HOST } from '../constant';
import { OSS_BASE_PATH_PREFIX, GAME_SHARE_TITLE, TASK_CONDITION_TYPE, CODE_SUCCESS } from './constant';
import scratchCocver from './assets/image/ipland/scratchCocver.png';
import StrategyModal from './components/StrategyModal/StrategyModal';
import TaskModal from './components/TaskModal/TaskModal';
import PropModal from './components/PropModal/PropModal';
import ResultModal from './components/ResultModal/ResultModal';
import MemberModal from './components/MemberModal/MemberModal';
import DailyExclusiveModal from './components/DailyExclusiveModal/DailyExclusiveModal';

/**
 * Class Scratch
 * @class
 * @classdesc 九宫格翻纸牌组件逻辑部分
 * @author pfan
 * @todo 1.drawImage 与 clearRect 清除展示移动端和模拟器不一致
 * @todo 2.小程序无globalCompositeOperation = 'destination-out'属性
 * @todo 3.小程序无getImageData获取像素点对比擦除范围
 * @todo 4.使用 downloadFile 这种方式来先加载图片再绘制
 *
 * @example
 *  new Scratch(this,{
 *    canvasWidth: 197,   //画布宽带
 *    canvasHeight: 72,  //画布高度
 *    imageResource: './images/placeholder.png', //遮罩层图片
 *    r: 4, //笔触半径
 *    awardTxt: '中大奖', //底部抽奖文字奖项
 *    awardTxtColor: "#1AAD16", //底部抽奖文字颜色
 *    awardTxtFontSize: "24px", //底部抽奖文字大小
 *    maskColor: "red",  //没有图片遮罩层颜色
 *    callback: () => {
 *      //清除画布回调
 *    }
 *  })
 */

//@ts-ignore
actions().actions.loadReducer();
//@ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class packageIScratch extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      query: {}, // 路径中携带参数
      isStart: false,
      ctx: null,
      r: 10,
      lastX: 0,
      lastY: 0,
      minX: '',
      minY: '',
      maxX: '',
      maxY: '',
      canvasWidth: 300,
      canvasHeight: 175,
      pics: {
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
      },
      tempFilePath: '',
      selectedProp: null, // 选择道具
    };
  }
  componentDidShow() {
    let { actions: { action } } = this.props;
    // 获取路由参数
    this.handleGetRouterParams();
    Taro.showLoading();
    // 查询用户信息-领取每日赠送游戏次数
    action.loadUserInfo().then((res) => {
      this.canvasInit();
      this.start();
    }),
    // 查询游戏任务列表
    this.handleQueryTaskItems({});
    // 查询道具列表
    this.handleQueryPropItems({});
    // 查询游戏可玩次数
    // this.props.actions.action.loadGameTimes();
    // 查询当前剩余可玩游戏次数
    action.loadGameDailyLeftTimes();
    // 查询游戏信息
    action.loadGameInfo();
    // 查询新人保障
    action.loadUserIsNewComer();
    // 获取游戏信息
    // this.props.actions.action.gameLottery({});
  }

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    console.log('catching handleGetRouterParams params', params);
    if (params.favorite || params.share) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
    }
    Taro.setStorageSync('scratch_task_query', params);
  };

  componentWillMount() {
    if (__TARO_ENV !== 'h5') {
      Taro.showShareMenu({
        withShareTicket: true,
      });
    }
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    // 查询每日游戏次数如果有信息，则不进行弹框提示
    if (nextProps.main.status.loadingGameDaily == false && this.props.main.status.loadingGameDaily == true) {
      if (nextProps.main.response.loadGameDaily == CODE_SUCCESS) {
        // this.props.actions.action.commonChange('main.showDailyExclusiveModal',true)
        console.log('今日领取记录');
        // 无信息则弹出开心收下弹框
        // if (!nextProps.main.gameReceiveInfo.id) {
        // this.props.actions.action.commonChange('main.showDailyExclusiveModal',true)
        // }
      }
      // 获取游戏次数
      // this.props.actions.action.loadGameTimes();
    }

    // const {query} = this.state;
    // 开始抽奖
    if (nextProps.main.status.loadingGameLottery == false && this.props.main.status.loadingGameLottery == true) {
      // 做任务的哦
      // if (query && query.taskId && query.taskConditionsType) {
      //   console.log('catchplaything task_condition_type', TASK_CONDITION_TYPE['game'], query.taskConditionsType);
      //   if (query.taskConditionsType == TASK_CONDITION_TYPE['game']) {
      //   }
      // }
    }
  }
  onTouchStart(e) {
    let {
      main: { gameTimes, gameDailyLeftTimes },
    } = this.props;
    if (gameTimes <= 0) {
      this.haveNoGameTimes();
      return;
    } else {
      if (gameDailyLeftTimes == 0) {
        Taro.showToast({
          title: '今日游戏次数已达上限！',
          icon: 'none',
        });
        return;
      }
    }
    let { isStart, ctx } = this.state;
    if (!isStart) return;
    const pos = this.drawRect(e.touches[0].x, e.touches[0].y);
    ctx.clearRect(pos[0], pos[1], pos[2], pos[2]);
    ctx.draw(true);
  }

  drawRect(x, y) {
    let { r, minX, minY, maxX, maxY, lastX, lastY } = this.state;
    const x1 = x - r > 0 ? x - r : 0;
    const y1 = y - r > 0 ? y - r : 0;
    if ('' != minX) {
      minX = minX > x1 ? x1 : minX;
      minY = minY > y1 ? y1 : minY;
      maxX = maxX > x1 ? maxX : x1;
      maxY = maxY > y1 ? maxY : y1;
    } else {
      minX = x1;
      minY = y1;
      maxX = x1;
      maxY = y1;
    }
    lastX = x1;
    lastY = y1;

    this.setState({
      lastX,
      lastY,
      minX,
      minY,
      maxX,
      maxY,
    });

    return [x1, y1, 2 * r];
  }

  onTouchMove(e) {
    let {
      main: { gameTimes, gameDailyLeftTimes },
    } = this.props;
    if (gameTimes <= 0) {
      this.haveNoGameTimes();
      return;
    } else {
      if (gameDailyLeftTimes == 0) {
        Taro.showToast({
          title: '今日游戏次数已达上限！',
          icon: 'none',
        });
        return;
      }
    }
    let { isStart, ctx } = this.state;
    const pos = this.drawRect(e.touches[0].x, e.touches[0].y);
    ctx.clearRect(pos[0], pos[1], pos[2], pos[2]);
    ctx.draw(true);
  }

  onTouchEnd(e) {
    let { isStart, ctx } = this.state;
    // 自动清楚采用点范围值方式判断
    const { canvasWidth, canvasHeight, minX, minY, maxX, maxY } = this.state;
    // if (maxX - minX > .5 * canvasWidth && maxY - minY > .5 * canvasHeight) {
    if (maxX - minX > 0.2 * canvasWidth && maxY - minY > 0.2 * canvasHeight) {
      ctx.draw();

      // 完成任务
      this.handleComputedTask();

      // 完成游戏
      const { selectedProp } = this.state;
      // 判断是否使用道具
      if (selectedProp && selectedProp.propId) {
        this.props.actions.action.gameLottery({
          propId: selectedProp.propId,
          myPropId: selectedProp.id,
        });
      } else {
        this.props.actions.action.gameLottery({});
      }

      this.setState({
        isStart: false,
      });
      this.props.actions.action.commonChange('main.isScroll', true);
    }
  }

  canvasInit() {
    let { ctx, canvasWidth, canvasHeight } = this.state;
    ctx = wx.createCanvasContext('myCanvas');
    this.setState({
      ctx: ctx,
    });
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    // if (imageResource && imageResource != '') {
    wx.downloadFile({
      url: `${IPLAND_OSS_HOST}scratch/scratchCocver.png`,
      success: (res) => {
        this.setState({ tempFilePath: res.tempFilePath });
        ctx.drawImage(res.tempFilePath, 0, 0, canvasWidth, canvasHeight);
        ctx.draw();
        Taro.hideLoading();
      },
    });
    // ctx.drawImage(scratchCocver, 0, 0, canvasWidth, canvasHeight)
    // ctx.draw()
    //   } else {
    //   ctx.setFillStyle(maskColor)
    //   ctx.fillRect(0, 0, canvasWidth, canvasHeight)
    //   ctx.draw()
    // }
  }

  start() {
    let { isStart, ctx } = this.state;
    this.setState({
      isStart: true,
    });
    let {
      actions: { action },
      main: { isScroll },
    } = this.props;
    action.commonChange('main.isScroll', false);
  }

  restart() {
    this.setState({
      lastX: 0,
      lastY: 0,
      minX: 0,
      minY: '',
      maxX: 0,
      maxY: 0,
      isStart: true,
    });

    let {
      actions: { action },
      main: { isScroll },
    } = this.props;
    action.commonChange('main.isScroll', true);
  }

  // 没有游戏次数
  haveNoGameTimes() {
    let {
      main: { isAquamarineMember, isCrystalMember },
    } = this.props;
    if (!isAquamarineMember && !isCrystalMember) {
      // 显示开通会员弹窗
      this.hideCanvas();
      this.props.actions.action.commonChange('main.showOpenMemberModal', true);
    } else {
      Taro.showToast({
        title: '做任务获取次数吧',
        icon: 'none',
      });
    }
  }

  /**
   * 查询游戏任务列表
   */
  handleQueryTaskItems = (pagation) => {
    // 编辑参数
    const {
      main: {
        task: { page },
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadTaskItems(params);
  };

  /**
   * 取消道具使用
   */
  handleCancelSelectProp = (type) => {
    // 取消选中就不关
    if (type != 'selectedCancel') {
      // this.handleModalShowAndHide('', false); // 关闭模态框
      this.props.actions.action.commonChange('main.showPropModal', false);
      this.showCanvas();
    } else {
      this.setState({
        selectedProp: null,
      });
    }
  };

  /**
   * 选择道具
   */
  handleUseSelectProp = (data) => {
    console.log('index.tsx handleUseSelectProp data', data);
    this.setState({
      selectedProp: data,
    });
    this.props.actions.action.commonChange('main.showPropModal', false);
    this.showCanvas();
    this.setState({
      selectedProp: data,
    });
  };

  /**
   * 查询道具信息
   */
  handleQueryPropItems = (pagation) => {
    const {
      main: {
        prop: { page },
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadPropItems(params);
  };

  showCanvas() {
    this.props.actions.action.commonChange('main.showCanvas', true);
    // let {tempFilePath} = this.state;
    // let {ctx, canvasWidth, canvasHeight} = this.state;
    // ctx.drawImage(tempFilePath, 0, 0, canvasWidth, canvasHeight);
    // ctx.draw();
    // let { tempFilePath } = this.state
    // let { ctx, canvasWidth, canvasHeight } = this.state;
    // ctx.drawImage(tempFilePath, 0, 0, canvasWidth, canvasHeight);
    // ctx.draw();
    // setTimeout(() => {
    //   this.props.actions.action.commonChange('main.showAwardTxt', true);
    // }, 800);
    setTimeout(() => {
      Taro.showLoading();
      this.canvasInit();
      this.restart();
    }, 500);
  }

  hideCanvas() {
    this.props.actions.action.commonChange('main.showCanvas', false);
    // this.props.actions.action.commonChange('main.showAwardTxt', false);
  }

  render() {
    let {
      main: {
        isScroll,
        showGameOverModal,
        showAwardTxt,
        showTaskModal,
        showStrategyModal,
        showPropModal,
        gameTimes,
        isNewComer,
        gameLotteries,
        showCanvas,
        showOpenMemberModal,
        showDailyExclusiveModal,
        isAquamarineMember,
        isCrystalMember,
      },
      actions: { action },
    } = this.props;
    let { tempFilePath, selectedProp } = this.state;
    return (
      <View className="packageIScratch">
        <Image className="logo" src={`${IPLAND_OSS_HOST}scratch/guaguale.png`}></Image>
        <Image className="gift" src={`${IPLAND_OSS_HOST}scratch/gift.png`}></Image>

        <View
          className="scratch_wp"
          style={{
            position: 'relative',
            width: '300px',
            height: '175px',
            backgroundColor: '#fff',
            margin: '0 auto',
          }}
        >
          {showCanvas && (
            <Canvas
              canvas-id="myCanvas"
              className="myCanvas"
              style={{
                margin: '0 auto',
                width: '300px',
                height: '175px',
                // background: 'transparent',
                // zIndex: 2,
              }}
              onTouchStart={this.onTouchStart.bind(this)}
              onTouchMove={this.onTouchMove.bind(this)}
              onTouchEnd={this.onTouchEnd.bind(this)}
              disable-scroll={isScroll}
            ></Canvas>
          )}
          {/* {showAwardTxt && (
              <Text
                className="scratch_txt"
                style={{
                  position: 'absolute',
                  top: '0',
                  left: '0',
                  width: '100%',
                  height: '100%',
                  textAlign: 'center',
                  lineHeight: '175px',
                  color: '#3985ff',
                  fontSize: '30px',
                  // zIndex: 1,
                }}
              >
                {(gameLotteries.length > 0 && gameLotteries[0].name) || '谢谢参与'}
              </Text>
            )} */}
        </View>

        <Text className="leftCount">您今天还有{gameTimes}次抽奖机会</Text>
        {isNewComer && <Text className="newer">新人加成生效中</Text>}
        <Text
          className="strategy"
          onClick={() => {
            this.hideCanvas();
            action.commonChange('main.showStrategyModal', true);
          }}
        >
          欧气攻略
        </Text>
        <View
          className="operate"
          onClick={() => {
            this.hideCanvas();
            action.commonChange('main.showPropModal', true);
          }}
        >
          <Image className="prop" src={`${OSS_BASE_PATH_PREFIX}/propBuffIcon.png`}></Image>
          <Text className="drawText">魔力进阶</Text>
        </View>
        <View
          className="operate task"
          onClick={() => {
            this.hideCanvas();
            // 判断是否是会员，只有会员才能打开任务
            if (isAquamarineMember || isCrystalMember) {
              action.commonChange('main.showTaskModal', true);
            } else {
              action.commonChange('main.showOpenMemberModal', true);
            }
          }}
        >
          <Image className="count" src={`${IPLAND_OSS_HOST}scratch/draw.png`}></Image>
          <Text className="drawText">领次数</Text>
        </View>
        {/* 游戏结束 */}
        <ResultModal
          onPlayAgain={() => {
            this.props.actions.action.commonChange('main.showGameOverModal', false);
            this.showCanvas();
          }}
          visible={showGameOverModal}
          onCancel={() => {
            action.commonChange('main.showGameOverModal', false);
            this.showCanvas();
          }}
        />
        {/* 欧气攻略 */}
        <StrategyModal
          visible={showStrategyModal}
          onCancel={() => {
            action.commonChange('main.showStrategyModal', false);
            this.showCanvas();
          }}
        />
        {/* 任务 */}
        <TaskModal
          visible={showTaskModal}
          onCancel={() => {
            action.commonChange('main.showTaskModal', false);
            this.showCanvas();
          }}
          onQueryTask={this.handleQueryTaskItems}
        />
        {/* 魔力进阶 */}
        <PropModal
          selectItem={selectedProp}
          visible={showPropModal}
          onCancel={(type) => {
            this.handleCancelSelectProp(type);
          }}
          onUse={this.handleUseSelectProp}
          onQueryProp={this.handleQueryPropItems}
        />
        {/* 开通会员 */}
        <MemberModal
          visible={showOpenMemberModal}
          onCancel={() => {
            action.commonChange('main.showOpenMemberModal', false);
            this.showCanvas();
          }}
          onActivate={() => this.handleActivateMember()}
        />
        {/* 每日领取奖励 */}
        <DailyExclusiveModal
          visible={showDailyExclusiveModal}
          onCancel={this.handleCancelGameTimesDaily}
          onReceive={this.handleReceive}
        />
      </View>
    );
  }

  /**
   * 确定开通会员
   */
  handleActivateMember = () => {
    this.props.actions.action.commonChange('main.showOpenMemberModal', false);
    this.showCanvas();
    // 跳转到开通会员界面
    Taro.navigateTo({
      url: '/pages/package-A/memberOpen/index',
    });
  };

  /**
   * 点击开心收下
   */
  handleReceive = () => {
    console.log('index.tsx handleReceive');
    this.props.actions.action.commonChange('main.showDailyExclusiveModal', false);
    this.handleQueryGameTimesReceiveDaily(false);
  };

  /**
   * 取消
   */
  handleCancelGameTimesDaily = () => {
    this.props.actions.action.commonChange('main.showDailyExclusiveModal', false);
    this.handleQueryGameTimesReceiveDaily(true);
  };

  /**
   * 每日领取：收下or拒绝
   */
  handleQueryGameTimesReceiveDaily = (type) => {
    this.showCanvas();
    console.log('index.tsx handleQueryGameTimesDaily type', type);
    let params = {
      delFlag: type,
    };
    this.props.actions.action.loadGameTimesReceiveDaily(params);
  };

  /**
   * 分享好友
   * @param res
   * @returns
   */
  onShareAppMessage(res) {
    const {
      pics: { gameShareThum },
    } = this.state;
    let query = Taro.getStorageSync('scratch_task_query');
    if (query && query.taskConditionsType == TASK_CONDITION_TYPE['share']) {
      this.props.actions.action.computedTask({
        id: query.taskId,
        taskConditionsType: query.taskConditionsType,
      });
      Taro.removeStorageSync('scratch_task_query');
    }

    return {
      title: GAME_SHARE_TITLE,
      path: '/pages/package-I/home/index',
      imageUrl: gameShareThum,
      query: 'share=true',
    };
  }

  /**
   * 完成任务
   */
  handleComputedTask() {
    let query = Taro.getStorageSync('scratch_task_query');
    if (query && query.taskId && query.taskConditionsType) {
      console.log('catchplaything task_condition_type', TASK_CONDITION_TYPE['game'], query.taskConditionsType);
      if (query.taskConditionsType == TASK_CONDITION_TYPE['game']) {
        this.props.actions.action.computedTask({
          id: query.taskId,
          taskConditionsType: query.taskConditionsType,
        });
      }
    }
  }

  /**
   * 分享到朋友圈
   * @param res
   * @returns
   */
  onShareTimeline(res) {
    const {
      pics: { gameShareIcon },
    } = this.state;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      path: '/pages/package-I/home/index',
      query: 'share=true',
    };
  }

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: { gameShareIcon },
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}

//create by moon https://github.com/creasy2010/moon
